package com.huawei.esdk.uc.sametime;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import com.huawei.esdk.uc.jna.Constants;
import com.huawei.esdk.uc.sametime.ConstantsDefines.CallStatus;
import com.huawei.esdk.uc.sametime.services.UCCallService;
import com.huawei.esdk.uc.sametime.services.UCLoginService;
import com.huawei.esdk.uc.sametime.util.GlobalConfiguration;
import com.huawei.esdk.uc.sametime.util.ImageFactory;
import com.huawei.esdk.uc.sametime.util.PluginUtil;
import com.huawei.esdk.uc.sametime.widgets.CallComeInPopup;
import com.huawei.esdk.uc.sametime.widgets.EsdkUCConvWindow;
import com.ibm.collaboration.realtime.people.Person;

/**
 * The activator class controls the plug-in life cycle 插件生命周期管理
 * @author y00175154
 */
public class EsdkPluginActivator extends AbstractUIPlugin
{

    private static Logger logger = Logger.getLogger(EsdkPluginActivator.class);

    // The plug-in ID
    public static final String PLUGIN_ID = "com.huawei.esdk.uc.sametime";

    // The shared instance
    private static EsdkPluginActivator plugin;

    private HashMap<String, Person> personMap = new HashMap<String, Person>();

    /**
     * The constructor
     */
    public EsdkPluginActivator()
    {
        EsdkPluginActivator.initPlugin(this);
    }

    public Map<String, Person> getPersonMap()
    {
        return personMap;
    }

    /*
     * 插件启动时候调用此方法.在这个方法中,初始化UCsdk并做UC登录
     * 
     * @see
     * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
     * )
     */
    public void start(BundleContext context) throws Exception
    {
        super.start(context);
        PluginUtil.confiLog4jProperties();
        logger.debug("plugin start");
        // simulates the mechanism that would generate status image updates.
        // this could be a polling thread that queries a telephony server to get
        // status at some regular interval, or an application that listens for
        // broadcast events.
        // plugin = this;
        EsdkPluginActivator.initPlugin(this);
        logger.debug("current charset: "
                + Charset.defaultCharset().displayName());
        loadUCLib();
        // 插件启动时候,uc和sametime必须先设置成未登录,之后的状态才好控制
        GlobalConfiguration.getInstance().resetAllConfig();

        UCLoginService.initSDK();
    }

    /*
     * 插件被停掉时候调用.在这里做登出和ucsdk卸载
     * 
     * @see
     * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
     * )
     */
    public void stop(BundleContext context) throws Exception
    {
        logger.debug("plugin stop");

        // 释放图片资源
        ImageFactory.dispose();

        // plugin = null;
        EsdkPluginActivator.initPlugin(null);

        if (CallStatus.end != UCCallService.getCallStatus())
        {
            CallComeInPopup.getInstance().closeComeInPopup();
            EsdkUCConvWindow.getInstance().endCall();

            Thread.currentThread();
            Thread.sleep(2 * 1000);
        }

        int logoutCounter = 0;
        if (GlobalConfiguration.getInstance().isUCLogin())
        {
            UCLoginService.startLogoutUC();

            while (GlobalConfiguration.getInstance().isUCLogin()
                    && logoutCounter < ConstantsDefines.MAX_TRY_TIMES)
            {
                Thread.currentThread();
                Thread.sleep(500);
                logoutCounter++;
                logger.debug("GlobalConfiguration.getInstance().isUCLogin() :"
                        + GlobalConfiguration.getInstance().isUCLogin()
                        + ",and logoutCounter is:" + logoutCounter);
            }
        }

        if (GlobalConfiguration.getInstance().isUCInit())
        {
            int ret = UCLoginService.unInitSDK();
            if (Constants.UCServiceRetvCode.UC_SDK_Success == ret)
            {
                logger
                        .debug("unInitSDK when uc not login | GlobalConfiguration.getInstance().isUCInit() :"
                                + GlobalConfiguration.getInstance().isUCInit());
            }
        }

        if (ConstantsDefines.MAX_TRY_TIMES < logoutCounter)
        {
            int initCounter = 0;
            while (GlobalConfiguration.getInstance().isUCInit()
                    && initCounter < ConstantsDefines.MAX_TRY_TIMES)
            {
                Thread.currentThread();
                Thread.sleep(500);
                initCounter++;
                logger.debug("GlobalConfiguration.getInstance().isUCInit() :"
                        + GlobalConfiguration.getInstance().isUCInit()
                        + ",and try count: " + initCounter);
            }
        }

        super.stop(context);
    }

    /**
     * Returns the shared instance
     * 
     * @return the shared instance
     */
    public static EsdkPluginActivator getDefault()
    {
        return plugin;
    }

    public static void initPlugin(EsdkPluginActivator activator)
    {
        plugin = activator;
    }

    public void loadUCLib()
    {
        DllLoader loader = new DllLoader();
        loader.loadPropertyConfig();
        loader.sequenceLoadDll();
        loader.clear();
    }

}
